package com.intramirror.wd.business.config;

import com.intramirror.common.jdbc.persistence.datasource.ReadWriteDataSourceDecision;
import com.intramirror.common.jdbc.persistence.datasource.ReadWriteDataSourceProcessor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by zhongyu on 2018/3/30.
 */
@Aspect
@Component
public class DetermineDatasourceAspect implements Ordered {

    @Around("execution(* com.intramirror.wd.business.manage.*.*(..))")
    public Object processTx(ProceedingJoinPoint jp) throws Throwable{
        Long start = System.currentTimeMillis();
        if (isChoiceReadDB(jp.getSignature().getName())) {
            ReadWriteDataSourceDecision.markRead();
        } else {
            ReadWriteDataSourceDecision.markWrite();
        }
        try {
            Long end = System.currentTimeMillis();
            Object obj = jp.proceed();
            System.out.println("choice db wast time : " + (System.currentTimeMillis() - start) + ", sign time:" + (end - start));
            return obj;
        } finally {
            ReadWriteDataSourceDecision.reset();
        }
    }

    private boolean isChoiceReadDB(String name) {
        return !name.endsWith("WithTx");
    }

    @Override
    public int getOrder() {
        return -2147483648;
    }
}
